# -*- coding:utf-8 -*-
import ctypes,sys,psutil,tkinter.messagebox,getpass,signal
import os
from main.main_public import get_pid_name
from main.main_form import MainForm

# 打包失败提示没有找到这个模块名称，请在spec文件中hiddenimports项添加即可，pyinstaller默认打包时不会打包第三方库，缺失的请添加！
username = getpass.getuser()
# 创建临时文件夹
make_dir = 'C:\\Users\\' + username + '\\Documents\\DA_Tools\\'
# 记录个人打印日志（方便看问题）
log_path = make_dir + 'main_log.log'
tools_start_flag = make_dir + 'tool_start.log'
tools_close_flag = make_dir + 'tool_close.log'


# def proc_exist(process_name):
#     is_exist = False
#     wmi = win32com.client.GetObject('winmgmts:')
#     processCodeCov = wmi.ExecQuery('select * from Win32_Process where name=\"%s\"' %(process_name))
#     if len(processCodeCov) > 0:
#         is_exist = True
#     return is_exist


def run_program():
    main = MainForm()
    # adb_form.root_form()

    def is_admin():
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            return False

    if is_admin():
        global flag

        # 此处为解决"_tkinter.TclError: image "pyimage1" doesn't exist"(多个根窗口冲突)问题的代码，其中tkinter为上方import的tkinter
        root_temporary = tkinter.Tk()
        root_temporary.withdraw()

        if not os.path.exists(tools_start_flag):  # 避免重复打开应用
            with open(tools_start_flag,'w') as fp:
                fp.write('first')
        if not os.path.exists(tools_close_flag):  # 避免重复打开应用
            with open(tools_close_flag,'w') as fp:
                fp.write('end')
        flag = open(tools_start_flag,'r').read()
        close_flag = open(tools_close_flag,'r').read()
        if flag == 'first' and close_flag != 'end':
            with open(tools_start_flag, 'w') as fp:
                fp.write('first')
            flag = open(tools_start_flag, 'r').read()
            tkinter.messagebox.showinfo('意外异常退出','本工具非正常退出，可能会导致功能异常！')
        elif flag != 'first' and close_flag != 'end':
            my_pid_list = []
            pid = os.getpid()  # 获取当前程序pid
            pid_name = psutil.Process(pid).name()  # 根据pid获取当前程序名
            pid_name_list = get_pid_name()
            with open(log_path, 'w') as fp:
                fp.write('当前计算机所有进程:{}'.format(pid_name_list))
            for pid_name_i in pid_name_list:
                if pid_name_i == pid_name:
                    my_pid_list.append(pid_name_i)
            if len(my_pid_list) == 2:  # 应用启动后分前台和后台进程两个进程
                with open(tools_start_flag, 'w') as fp:
                    fp.write('first')
                flag = open(tools_start_flag, 'r').read()
                tkinter.messagebox.showinfo('意外异常退出', '本工具非正常退出，可能会导致功能异常！')
            elif len(my_pid_list) > 2:
                with open(log_path, 'a+') as fp:
                    fp.write('\n[>2]当前程序名称:{}'.format(my_pid_list))
                # print('my_pid_list:{}'.format(my_pid_list))
                # print('进来了！')
                tkinter.messagebox.showinfo('打开失败', '已经有一个程序在运行中，无法重复打开！')
                pid = os.getpid()  # 获取本工具的pid
                os.kill(pid, signal.SIGINT)  # 避免残留后台运行强制杀死
                sys.exit()  # 退出程序
        if flag == 'first':
            with open(tools_start_flag,'w') as fp:
                fp.write('')
            with open(tools_close_flag,'w') as fp:
                fp.write('')

            # 及时销毁之前解决问题的窗口，以免冲突发生异常
            root_temporary.destroy()

            main.root_form()
    else:
        ctypes.windll.shell32.ShellExecuteW(None, 'runas', sys.executable, __file__, None, 1)


run_program()


